from rest_framework import serializers
from api import models
from rest_framework import exceptions
from django.db.models import Max


class BidModelSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    username = serializers.CharField(source='user.nickname', read_only=True)

    class Meta:
        model = models.BidRecord
        fields = ['id', 'price', 'item', 'status_text', 'username']

    def validate_item(self, value):
        exists = models.AuctionItem.objects.filter(id=value.id, status=3).exists()
        if not exists:
            raise exceptions.ValidationError('已拍卖完成或未开拍')
        return value

    def validate_price(self, attrs):

        item_id = self.initial_data.get('item')
        item_object = models.AuctionItem.objects.filter(id=item_id).first()
        if attrs <= item_object.start_price:
            raise exceptions.ValidationError("不能低于起拍价")
        div = (attrs - item_object.start_price) % item_object.unit
        if div:
            raise exceptions.ValidationError('必须按照加价幅度来竞价')
        # 获取最高价
        max_price = self.context['view'].queryset.filter(item=item_object).aggregate(max_price=Max('price'))[
            'max_price']
        if not max_price:
            return attrs
        if max_price >= attrs:
            raise exceptions.ValidationError("价格不能小于等于竞拍价")
        return attrs
